Home:ALL Converter>Error [ERR_HTTP_HEADERS_SENT]: Cannot remove headers after they are sent to the client

Error [ERR_HTTP_HEADERS_SENT]: Cannot remove headers after they are sent to the client

Ask Time:2020-04-01T01:30:25         Author:Emanuele

Json Formatter

I am performing a simple API fetch but I am receiving the following error:

UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot remove headers after they are sent to the client and I am not sure why that is happening:

Code is below and also a print screen of the error is provided. I am not sure if that could be a problem related to the asynchronous behavior of nodejs:

var express = require('express');
var router = express.Router();
var axios = require('axios');
const NodeCache = require('node-cache');
const myCache = new NodeCache();

let hitCount = 0;

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express' });
});


router.get('/hello', async function(req, res, next) {
    const allData = myCache.get('allData');

    if (!allData) {
        hitCount++;
        console.log(`hit ${hitCount} number of times`);
        try {
            const { data } = await axios.get(
                'https://api.vesselfinder.com/vesselslist?userkey=KEY'
            );
            const [ metaData, ships ] = data;
            myCache.set('allData', data, 70);
            console.log(data + 'This is the data');
            res.send(data);
        } catch (error) {
            res.send(error);
            console.log(error);
        }
    }
    console.log('this is the data:', allData);
    res.send(allData);
});

module.exports = router;

What I have done so far to solve this error was:

I used this source which has a wide explanation of the what the problem could be with a broad explanation of the errors type. However it was not useful to understand what was going on.

Also I found this useful and also this but this last one in particular was an error in the code for a missing statement return. My error seems to be related to a TypeError: data is not iterable but it is not possible because my subscription with the provided is perfectly working.

The closest post I found is this one which basically states that "Sometimes it happens due to asynchronous behavior of nodejs." Now I see this happened to me but I am not sure how this could be solved in this situation.

A log of the error is also shown here in the print screen below for completeness:

error

What can I do to take care of this error? I did a lot of research and I am not sure how to take care of the asynchronous behavior of nodejs. Thank for pointing to the right direction for solving this problem.

Author:Emanuele,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/60956510/error-err-http-headers-sent-cannot-remove-headers-after-they-are-sent-to-the
yy